package com.globallogic.dailyplanner.utils;


import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;


import com.globallogic.dailyplanner.dto.User;
import com.globallogic.dailyplanner.service.UserService;


@Component
@Scope("request")
public class EmailValidator implements Validator{
private static final String USERNAME_PATTERN = "^[_A-Za-z0-9-]+"
                + "(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+"
                + "(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; 
        
        @Autowired
        private UserService userService;
        private Pattern pattern;
        private Matcher matcher; 
        
        public EmailValidator() {
                pattern = Pattern.compile(USERNAME_PATTERN);
                
        }


        public void validate(FacesContext arg0, UIComponent arg1, Object value)
                        throws ValidatorException {
                String email = value.toString();
                matcher = pattern.matcher(email);
                
                if(!matcher.matches()){
                         
                        FacesMessage msg = 
                                new FacesMessage("Email validation failed.", 
                                                "Email does not match pattern.");
                        msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                        throw new ValidatorException(msg);
                }
                
                List<User> users = userService.getAll();
                
                if ( users != null){
                        for(User user: users){
                                //TODO: change equals to apache common lang.
                                if (email.equals(user.getEmail())){
                                        FacesMessage msg = 
                                                        new FacesMessage("Email validation failed.", 
                                                                        "User with such email has already exist.");
                                                msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                                                throw new ValidatorException(msg);
                                }
                        }
                }
        }
}